package com.dragon.framework.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * MultipartFile序列化
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/17 15:52
 */
public class MultipartFileSerializer extends JsonSerializer<MultipartFile> {

    Logger log = LoggerFactory.getLogger(MultipartFileSerializer.class);


    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     *                    serializing Objects value contains, if any.
     */
    @Override
    public void serialize(MultipartFile value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();

        if (value != null) {
            try {
                gen.writeStringField("fileName", value.getOriginalFilename());
                gen.writeStringField("contentType", value.getContentType());
                gen.writeStringField("size", String.valueOf(value.getSize()));
            } catch (Exception e) {
                log.error("MultipartFile序列化异常 {}", e.getMessage(), e);
            }
        }

        gen.writeEndObject();
    }

}
